import time

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select

# 1. 创建浏览器驱动对象
driver = webdriver.Chrome()
driver.maximize_window()
# 设置隐式等待
driver.implicitly_wait(10)

# 2. 通过get方法获取网页并登录
driver.get("http://localhost:82/")
driver.find_element(By.PARTIAL_LINK_TEXT, "登录").click()
driver.find_element(By.ID, "username").send_keys("13800138006")
driver.find_element(By.ID, "password").send_keys("123456")
driver.find_element(By.ID, "verify_code").send_keys("8888")
driver.find_element(By.CLASS_NAME, "J-login-submit").click()
time.sleep(1)

# 进入个人中心
driver.find_element(By.CSS_SELECTOR, ".red.userinfo").click()
time.sleep(1)

# 点击【账户设置】下【收货地址】
driver.find_element(By.CSS_SELECTOR, "div[class='u-dt'] span").click()
driver.find_element(By.XPATH, "/html/body/div[2]/div/div[3]/ul/li[2]/div/div[2]/a[2]").click()
time.sleep(1)
# 查看地址最后一个并点击
time.sleep(1)
# 定位所有收货地址元素
address_list_container = driver.find_element(By.CSS_SELECTOR, ".menumain.p")
# 3. 定位所有收货地址项元素
address_items = address_list_container.find_elements(By.CSS_SELECTOR, ".add_conta")
# 4. 统计行数（地址项数量）
row_count_frond = len(address_items)
print(f"新增前收货地址列表有 {row_count_frond} 行")

# 点击【增加新地址】
driver.find_element(By.CSS_SELECTOR, "span[class='co_blue']").click()
time.sleep(1)

# 收货人信息 = cus{当前时间}
consignee = f"cus{time.strftime('%Y%m%d%H%M%S')}"
driver.find_element(By.CSS_SELECTOR, "input[name='consignee'][type='text']").send_keys(consignee)
time.sleep(1)

# 填写其他地址信息
driver.find_element(By.CSS_SELECTOR, "input[placeholder='固话号码格式:xx-xx(例如: 0755-86140485)']").send_keys("17630135209")
time.sleep(0.5)
Select(driver.find_element(By.CSS_SELECTOR, "#province")).select_by_visible_text("河南省")
time.sleep(0.5)
Select(driver.find_element(By.CSS_SELECTOR, "#city")).select_by_visible_text("周口市")
time.sleep(0.5)
Select(driver.find_element(By.CSS_SELECTOR, "#district")).select_by_visible_text("川汇区")
time.sleep(0.5)
Select(driver.find_element(By.CSS_SELECTOR, "#twon")).select_by_visible_text("开发区")
time.sleep(0.5)
driver.find_element(By.CSS_SELECTOR, "input[placeholder='详细地址']").send_keys("周口艾腾教育")
time.sleep(0.5)
driver.find_element(By.CSS_SELECTOR, "input[name='zipcode']").send_keys("466000")
time.sleep(0.5)

# 完成新增地址操作
driver.find_element(By.CSS_SELECTOR, "#address_submit").click()
time.sleep(1)

# 控制滚动条移动到页面最底部
driver.execute_script("window.scrollTo(0, 800)")
time.sleep(1)

# 刷新下界面
driver.refresh()
time.sleep(2)

# 查看地址最后一个并点击
time.sleep(1)
# 定位所有收货地址元素
address_list_container = driver.find_element(By.CSS_SELECTOR, ".menumain.p")
# 3. 定位所有收货地址项元素
address_items = address_list_container.find_elements(By.CSS_SELECTOR, ".add_conta")
# 4. 统计行数（地址项数量）
row_count_behind = len(address_items)
print(f"收货地址列表共有 {row_count_behind} 行")

# 判断新增完后的地址条数是否+1
if row_count_behind == row_count_frond + 1:
    print("新增成功")
else:
    print("新增失败")

# 关闭浏览器对象
driver.quit()